package com.nowcoder.community.controller;

import com.nowcoder.community.entity.*;
import com.nowcoder.community.event.EventProducer;
import com.nowcoder.community.service.CommentService;
import com.nowcoder.community.service.DiscussPostService;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.utils.CommonUtil;
import com.nowcoder.community.utils.ConstantUtil;
import com.nowcoder.community.utils.HostHolder;
import com.nowcoder.community.utils.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Author: shuhuang
 * @description:
 * @Date: 2022/11/3 20:07
 * @Version java version 1.8
 */
@Controller
@RequestMapping("/discuss")
public class DiscussPostController {
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private UserService userService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private LikeService likeService;
    @Autowired
    private EventProducer eventProducer;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发布帖子
     */
    @PostMapping(path = "/add")
    @ResponseBody
    public String addDiscussPost(String title, String content) {
        User user = hostHolder.getUser();
       /* if (user == null) {
            return CommonUtil.getJSONString(403, "请先登录哦~");
        }*/
        DiscussPost discussPost = new DiscussPost();
        discussPost.setUserId(user.getId());
        discussPost.setTitle(title);
        discussPost.setContent(content);
        discussPost.setType(0);
        discussPost.setStatus(0);
        discussPost.setCreateTime(new Date());
        discussPostService.addDiscussPost(discussPost);

        //触发发帖事件
        Event event = new Event()
                .setTopic(ConstantUtil.TOPIC_PUBLISH)
                .setUserId(user.getId())
                .setEntityType(ConstantUtil.ENTITY_TYPE_POST)
                .setEntityId(discussPost.getId());
        eventProducer.fireEvent(event);

        //计算帖子的分数
        String postScoreKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(postScoreKey, discussPost.getId());

        //todo 报错的情况将来统一处理【用AOP切面】
        return CommonUtil.getJSONString(0, "发布成功！");
    }

    /**
     * 帖子详情页
     */
    @GetMapping(path = "/details/{discussPostId}")
    public String getDiscussPost(@PathVariable int discussPostId, Model model, Page page) {
        if (discussPostId == 0) {
            return "/error/404";
        }
        //帖子
        DiscussPost discussPost = discussPostService.findDiscussPostById(discussPostId);
        model.addAttribute("discussPost", discussPost);
        //作者
        User user = userService.findUserById(discussPost.getUserId());
        model.addAttribute("user", user);
        //点赞数量
        long likeCount = likeService.findEntityLikeCount(ConstantUtil.ENTITY_TYPE_POST, discussPostId);
        model.addAttribute("likeCount", likeCount);
        //点赞状态
        int likeStatus = hostHolder.getUser() == null ? 0
                : likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ConstantUtil.ENTITY_TYPE_POST, discussPostId);
        model.addAttribute("likeStatus", likeStatus);

        //评论信息的分页查询
        page.setLimit(5);
        page.setPath("/discuss/details/" + discussPostId);
        page.setRows(discussPost.getCommentCount());
        //评论列表
        List<Comment> commentList = commentService.findCommentsByEntity(ConstantUtil.ENTITY_TYPE_POST, discussPost.getId(), page.getOffset(), page.getLimit());
        //评论VO列表
        List<Map<String, Object>> commentVoList = new ArrayList<>();
        if (commentList != null) {
            for (Comment comment : commentList) {
                //评论列表
                Map<String, Object> commentVo = new HashMap<>();
                commentVo.put("comment", comment);
                //评论者
                commentVo.put("user", userService.findUserById(comment.getUserId()));
                //点赞数量
                likeCount = likeService.findEntityLikeCount(ConstantUtil.ENTITY_TYPE_REPLY, comment.getId());
                commentVo.put("likeCount", likeCount);
                //点赞状态
                likeStatus = hostHolder.getUser() == null ? 0
                        : likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ConstantUtil.ENTITY_TYPE_REPLY, comment.getId());
                commentVo.put("likeStatus", likeStatus);
                //回复列表【-1代表查询所有】
                List<Comment> replyList = commentService.findCommentsByEntity(ConstantUtil.ENTITY_TYPE_REPLY, comment.getId(), 0, -1);
                //回复Vo列表
                List<Map<String, Object>> replyVoList = new ArrayList<>();
                if (replyList != null) {
                    for (Comment reply : replyList) {
                        Map<String, Object> replyVo = new HashMap<>();
                        //回复
                        replyVo.put("reply", reply);
                        //回复者
                        replyVo.put("replyUser", userService.findUserById(reply.getUserId()));
                        //回复目标
                        User target = reply.getTargetId() == 0 ? null : userService.findUserById(reply.getTargetId());
                        replyVo.put("target", target);
                        //点赞数量
                        likeCount = likeService.findEntityLikeCount(ConstantUtil.ENTITY_TYPE_REPLY, reply.getId());
                        replyVo.put("likeCount", likeCount);
                        //点赞状态
                        likeStatus = hostHolder.getUser() == null ? 0
                                : likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ConstantUtil.ENTITY_TYPE_REPLY, reply.getId());
                        replyVo.put("likeStatus", likeStatus);

                        replyVoList.add(replyVo);
                    }
                }
                commentVo.put("replies", replyVoList);
                //回复数量
                int replyCount = commentService.findCountByEntity(ConstantUtil.ENTITY_TYPE_REPLY, comment.getId());
                commentVo.put("replyCount", replyCount);
                commentVoList.add(commentVo);
            }
        }
        model.addAttribute("comments", commentVoList);
        return "/site/discuss-detail";
    }

    //置顶
    @PostMapping(path = "/top")
    @ResponseBody
    public String setTop(int id) {
        discussPostService.updateType(id, 1);
        //触发发帖事件
        Event event = new Event()
                .setTopic(ConstantUtil.TOPIC_PUBLISH)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(ConstantUtil.ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);
        return CommonUtil.getJSONString(0);
    }

    //加精
    @PostMapping(path = "/wonderful")
    @ResponseBody
    public String setWonderful(int id) {
        discussPostService.updateStatus(id, 1);
        //触发发帖事件
        Event event = new Event()
                .setTopic(ConstantUtil.TOPIC_PUBLISH)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(ConstantUtil.ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);

        //计算帖子分数
        String postScoreKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(postScoreKey, id);

        return CommonUtil.getJSONString(0);
    }

    //删除
    @PostMapping(path = "/delete")
    @ResponseBody
    public String setDelete(int id) {
        discussPostService.updateStatus(id, 2);
        //触发删帖事件
        Event event = new Event()
                .setTopic(ConstantUtil.TOPIC_DELETE)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(ConstantUtil.ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);
        return CommonUtil.getJSONString(0);
    }
}
